package com.zhou.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhou.util.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 获取地址类
 */
@Slf4j
public class AddressUtil {

    // IP地址查询
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    // 未知地址
    public static final String UNKNOWN = "UnKnow";

    public static String getRealAddressByIP(String ip) {
        // 内网不查询
        if ("127.0.0.1".equals(ip)) {
            return "内网IP";
        }
        try {
            Map<String,String> par = new HashMap<>(2);
            par.put("ip",ip);
            par.put("json","true");
            String rspStr = HttpUtil.get(IP_URL,null, par,"GBK");
            if (StringTool.isEmpty(rspStr)) {
                log.error("获取地理位置异常 {}", ip);
                return UNKNOWN;
            }
            JSONObject obj = JSON.parseObject(rspStr);
            String region = obj.getString("pro");
            String city = obj.getString("city");
            return String.format("%s %s", region, city);
        } catch (Exception e) {
            log.error("获取地理位置异常 {}", ip);
        }
        return UNKNOWN;
    }
}
